﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Xml;
using System.Collections;

namespace Kaixin.House.Garden
{
    using Kaixin.Tools;

    public delegate void AntiTheiveTriggeredEvent(object sender, EventArgs e);

    public class AntiTheive
    {
        /// <summary>
        /// 1. Content  - list of 5 fruits
        /// 2. Question - a picture contains the order of the content
        /// 3. Answer   - give order according to the picture
        /// </summary>
        /// 

        private Network _network;
        private string _verify;
        private bool _Triggered = false;
        private bool _Passed = true;
        private object _TrigLock = new object();
        private object _PassLock = new object();
        private byte[] _Question = null;
        private ArrayList _Content = null;

        public event AntiTheiveTriggeredEvent AntiTheiveTriggered;

        public bool Triggered
        {
            get
            {
                return _Triggered;
            }
        }

        public void Trigger()
        {
            lock (_TrigLock)
            {
                if (!_Triggered)
                {
                    _Triggered = true;
                    _Passed = false;
                }
            }

            lock (_PassLock)
            {
                if (!_Passed)
                {
                    if (!TryAutoAnswer())
                    {
                        if (AntiTheiveTriggered != null)
                            AntiTheiveTriggered(this, new EventArgs());
                    }
                }
            }
        }

        // call this after the answer is right 
        private void Reset()
        {
            lock (_PassLock)
            {
                _Passed = true;
                _Triggered = false;
                _Content = null;
                _Question = null;
            }
        }

        public AntiTheive(Network network, string verify)
        {
            _network = network;
            _verify = verify;
        }

        public ArrayList GetContent()
        {
            return _Content;
        }

        private ArrayList _GetContent()
        {
            string url = Consts.RootURL + Consts.GardenAntiContentUrl +
                "?verify=" + _verify;

            try
            {
                string resp = _network.CallUrl(url);
                XMLParser parser = new XMLParser(resp);
                XmlNodeList nodelist = parser.GetNodeList("/data/faq");

                ArrayList cont = new ArrayList(nodelist.Count);

                for (int i = 0; i < nodelist.Count; i++)
                {
                    if (nodelist.Item(i).NodeType == XmlNodeType.Text)
                        continue;

                    XmlElement element = (XmlElement)nodelist.Item(i);
                    string id = element.GetElementsByTagName("id").Item(0).InnerText;

                    cont.Add(SeedList.GetSeedById(id));
                }

                return (ArrayList)cont.Clone();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public byte[] GetQuestion()
        {
            return _Question;
        }

        // PNG image data
        private byte[] _GetQuestion()
        {
            string url = Consts.RootURL + Consts.GardenAntiQuestionUrl +
                "?verify=" + _verify;

            byte[] data = _network.GetData(url);
            return data;
        }

        //
        // Answer format:
        // ,id1,id2,id3,id4,id5
        //
        public bool SendAnswer(string ans)
        {
            string url = Consts.RootURL + Consts.GardenAntiQnswerUrl +
                "?ordernum="+ ans +"&verify=" + _verify;

            string resp = _network.CallUrl(url);

            XMLParser parser = new XMLParser(resp);
            if ("succ".Equals(parser.GetNodeValue("/data/ret")))
            {
                Reset();
                return true;
            }
            else
                return false;
        }

        private bool TryAutoAnswer()
        {
            _Content = _GetContent();
            _Question = _GetQuestion();

            return false;
        }
    }
}
